package com.dhy.dbCore.transaction.util;

import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * 存放当前线程正在运行的事务的Connection
 * @author 大忽悠
 */
@Slf4j
public class TransactionResourceManager {
    /**
     * 存放connection
     */
    private static ThreadLocal<ConnectionHolder> resources=new ThreadLocal();

    public static ConnectionHolder getResource(){
        return resources.get();
    }

    public static void bindResource(ConnectionHolder resource){
        resources.set(resource);
    }

    public static void unbindResource(boolean closeConn){
        try {
            ConnectionHolder resource = getResource();
            Connection connection = resource.getConnection();
            resources.set(null);
            if(closeConn){
                connection.close();
            }
        } catch (SQLException e) {
           log.error("数据库连接释放出错: ",e);
        }
    }
}
